package com.aiyige.page.publish.guarantee;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.service.ApiService;
import com.aiyige.base.eventbus.EventSelectGuarantee;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.response.GetGuaranteeConfigsResponse;
import com.aiyige.page.publish.guarantee.adapter.GuaranteeAdapter;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.guarantee.model.GuaranteeResp;
import com.aiyige.page.publish.guarantee.util.GuaranteeUtil;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.GuaranteePage)
public class GuaranteePage extends AppCompatActivity {
    public static final String EXTRA_KEY_GUARANTEE_DATA = "com.aiyige.extra.EXTRA_KEY_GUARANTEE_DATA";
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    GuaranteeAdapter guaranteeAdapter;
    @Autowired
    boolean postEvent = false;
    @Autowired
    String subject;
    @Autowired
    GuaranteeItem[] preSelectArray;
    List<GuaranteeItem> preSelectList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_guarantee);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (TextUtils.isEmpty(subject)) {
            subject = "";
        }
        preSelectList = new LinkedList<>();
        if (preSelectArray != null) {
            for (GuaranteeItem guaranteeItem : preSelectArray) {
                preSelectList.add(guaranteeItem);
            }
        }
        titleTv.setText(R.string.guarantee);
        titleActionBtn.setText(R.string.finish);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        guaranteeAdapter = new GuaranteeAdapter();
        recyclerView.setAdapter(guaranteeAdapter);
        requestData();
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (postEvent) {
            EventBus.getDefault().post(EventSelectGuarantee.newBuilder()
                    .resultCode(EventSelectGuarantee.RESULT_CANCEL)
                    .build());
        }
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                setResult(RESULT_CANCELED);
                if (postEvent) {
                    EventBus.getDefault().post(EventSelectGuarantee.newBuilder()
                            .resultCode(EventSelectGuarantee.RESULT_CANCEL)
                            .build());
                }
                finish();
                break;
            case R.id.titleActionBtn:
                ArrayList<GuaranteeItem> selectList = new ArrayList<>();
                List<GuaranteeItem> guaranteeItemList = guaranteeAdapter.getData();
                for (GuaranteeItem guaranteeItem : guaranteeItemList) {
                    if (guaranteeItem.isSelected()) {
                        selectList.add(guaranteeItem);
                    }
                }
                Intent intent = new Intent();
                intent.putParcelableArrayListExtra(EXTRA_KEY_GUARANTEE_DATA, selectList);
                setResult(RESULT_OK, intent);
                if (postEvent) {
                    EventBus.getDefault().post(EventSelectGuarantee.newBuilder()
                            .resultCode(EventSelectGuarantee.RESULT_OK)
                            .guaranteeItemList(selectList)
                            .build());
                }
                finish();
                break;
        }
    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        List<GuaranteeItem> guaranteeItemList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(GuaranteePage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .getGuarantee(subject)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<GuaranteeResp> guaranteeRespList = JSON.parseArray(json, GuaranteeResp.class);
                for (GuaranteeResp guaranteeResp : guaranteeRespList) {
                    guaranteeItemList.add(GuaranteeItem.newBuilder()
                            .id(guaranteeResp.getId())
                            .title(guaranteeResp.getName())
                            .content(guaranteeResp.getDetail())
                            .build());
                }
                GuaranteeUtil.resumeSelect(guaranteeItemList, preSelectList);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                guaranteeAdapter.setNewData(guaranteeItemList);
            }
        }
    }
}
